﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class NetworkPlayerManager
{
    internal class ManagedNetworkPlayer
    {
        public NetworkPlayer networkPlayer;
        public bool inUse = false;
        public string name = "Unnamed";
    }

    private ManagedNetworkPlayer[] players;

    public NetworkPlayerManager(int maxPlayers)
    {
        players = new ManagedNetworkPlayer[maxPlayers];
        for (int i = 0; i < maxPlayers; i++) players[i] = new ManagedNetworkPlayer() { inUse = false };
    }

    public int AddPlayer(NetworkPlayer player)
    {
        int playerIndex = -1;
        for (int i = 0; i < players.Length && playerIndex < 0; i++)
        {
            if (!players[i].inUse) playerIndex = i;
        }

        if (playerIndex < 0) return playerIndex;

        players[playerIndex].inUse = true;
        players[playerIndex].networkPlayer = player;
        return playerIndex;
    }

    public bool DropPlayer(NetworkPlayer player)
    {
        int playerIndex = GetPlayerIndex(player);
        if (playerIndex < 0) return false;
        players[playerIndex].inUse = false;
        return true;
    }

    private int GetPlayerIndex(NetworkPlayer player)
    {
        int playerIndex = -1;
        for (int i = 0; i < players.Length && playerIndex < 0; i++)
        {
            if (players[i].networkPlayer.guid == player.guid) playerIndex = i;
        }
        return playerIndex;
    }

    internal void SetPlayerName(int remotePlayerIndex, string remotePlayerName)
    {
        players[remotePlayerIndex].name = remotePlayerName;
    }

    internal string GetPlayerName(NetworkPlayer player)
    {
        return players[GetPlayerIndex(player)].name;
    }

}
